const http = require('http');
const UserFunction = require("./user")
function createIO(app) {

    let server = http.createServer(app);
    //注意，websocket的握手是需要依赖http服务的，所以这里要把server传入进去。
    let io = require('socket.io')(server, { cors: true });

    const userServer = {};

    //有新的客户端连接时触发
    io.on('connection', async (socket) => {

        socket.on("login", (userId) => {
            console.log(`用户登录:${userId}`)
            if (!userServer.hasOwnProperty(userId)) {
                console.log("新用户已注册")
                userServer[userId] = socket
            }
            socket.on("disconnect", function () {
                console.log("客户端断开连接.")
                //遇到的坑 每次都要删除该socket连接 否则断开重连还是这个socket但是client端socket已经改变
                delete userServer[userId]
            })
            socket.send(userId)
        })

        //接收到消息时触发
        socket = UserFunction(socket, userServer)
        //发生错误时触发
        socket.on('error', function (err) {
            console.log(err);
        });
    });


    return server
}

module.exports = createIO